package com.na.tools.texturesplit;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class TextureTools {

	public static Collection<TextureFrame> parsePlist(File file) throws Exception {
		/**
		 * <plist>
		 * 	<dict>
		 * 		<key>frames</key>
		 * 		<dict>
		 * 			<key>xxx.png</key>
		 * 			<dict>frame</dict>
		 * 			<key>xxx.png</key>
		 * 			<dict>frame</dict>
		 * 		</dict>
		 * 	</dict>
		 * </plist>
		 */
		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
		Element root = doc.getDocumentElement();
		Node dict = getFirstChildElement(root);
		dict = getElementByKey(dict, "frames", "dict");
		if (dict == null) {
			return null;
		}
		NodeList nodes = dict.getChildNodes();
		File imageFile = getImageFile(file);
		TextureFrame.setBaseImage(imageFile);
		List<TextureFrame> frames = new ArrayList<TextureFrame>();
		String name = null;
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				Element ele = (Element) node;
				if ("key".equals(ele.getNodeName())) {
					name = ele.getTextContent().trim();
				} else if ("dict".equals(ele.getNodeName())) {
					node = getElementByKey(ele, "frame", "string");
					String pos = node.getTextContent().trim();
					int[] posInts = parsePlistPos(pos);
					boolean rotated = "true".equals(getElementByKey(ele, "rotated", null).getNodeName());
					TextureFrame frame = new TextureFrame(name, posInts[0], posInts[1], posInts[2], posInts[3], rotated);
					frames.add(frame);
				}
			}
		}
		
		return frames;
	}
	
	private static Node getFirstChildElement(Node node) {
		NodeList nodes = node.getChildNodes();
		for (int i = 0; i < nodes.getLength(); i++) {
			Node n = nodes.item(i);
			if (n.getNodeType() == Node.ELEMENT_NODE) {
				return n;
			}
		}
		return null;
	}
	
	private static Node getElementByKey(Node dict, String keyText, String nodeName) {
		NodeList nodes = dict.getChildNodes();
		boolean find = false;
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				if ("key".equals(node.getNodeName())
						&& (keyText == null || keyText.equals(node.getTextContent().trim()))) {
					find = true;
				} else if (find
						&& (nodeName == null || nodeName.equals(node.getNodeName()))) {
					return node;
				}
			}
		}
		return null;
	}
	
	private static File getImageFile(File plist) {
		String name = plist.getName();
		name = name.substring(0, name.lastIndexOf('.'));
		File[] files = plist.getParentFile().listFiles();
		for (File f : files) {
			if ((f.getName().endsWith(".png") || f.getName().endsWith(".jpg"))
					&& f.getName().startsWith(name)) {
				return f;
			}
		}
		return null;
	}
	
	private static int[] parsePlistPos(String pos) {
		String[] strs = pos.replaceAll("\\{", "").replaceAll("\\}", "").split(",");
		int[] r = new int[strs.length];
		for (int i = 0; i < strs.length; i++) {
			r[i] = Integer.parseInt(strs[i]);
		}
		return r;
	}
	
	private static Map<String, String> settings;
	public static String getSetting(String key) {
		loadSettings();
		return settings.get(key);
	}
	
	public static void loadSettings() {
		if (settings == null) {
			settings = new HashMap<String, String>();
			BufferedReader reader = null;
			try {
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File("settings.txt")), "UTF-8"));
				String line;
				while ((line = reader.readLine()) != null) {
					String[] strs = line.trim().split("=");
					settings.put(strs[0].trim(), strs[1].trim());
				}
			} catch (IOException e) {
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {}
				}
			}
		}
	}
	
	public static void saveSetting(String key, String value) {
		loadSettings();
		settings.put(key, value);
		saveSettings();
	}
	
	public static void saveSettings() {
		PrintWriter writer = null;
		try {
			File file = new File("settings.txt");
			if (!file.exists()) {
				if (file.getParentFile() != null)
					file.getParentFile().mkdirs();
				file.createNewFile();
			}
			writer = new PrintWriter(file, "UTF-8");
			for (Entry<String, String> entry : settings.entrySet()) {
				writer.println(entry.getKey() + "=" + entry.getValue());
			}
			writer.flush();
		} catch (IOException e) {
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}
	
}
